package com.alibaba.algo.core.base;

/**
 * Created by IntelliJ IDEA.
 * User: glorysongglory
 * Date: 2020/5/9
 * Time: 10:27
 */

import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.List;

@Data
@EqualsAndHashCode(callSuper = false)
public class Pager {
    private long total;
    private int totalPages;
    private int pageSize;
    private int pageIndex;
    private List<?> dataList;

    public static final int TEN = 10;

    private Pager() {
    }

    public int getStart() {
        return (pageIndex - 1) * pageSize;
    }

    public int getEnd() {
        return pageSize;
    }

    public static Pager newInstance(Long total, Integer pageIndex, Integer pageSize) {
        Pager p = new Pager();
        if (null == total) {
            total = 0l;
        }
        if (null == pageIndex) {
            pageIndex = 1;
        }
        if (null == pageSize) {
            pageSize = TEN;
        }
        if (pageIndex < 1)
            pageIndex = 1;
        if (pageSize < 1)
            pageSize = TEN;
        p.total = total;
        p.pageIndex = pageIndex;
        p.pageSize = pageSize;

        if (total % pageSize == 0) {
            p.totalPages = (int) (total / pageSize);
        } else {
            p.totalPages = (int) (total / pageSize + 1);
        }
        if (p.totalPages < 1) {
            p.totalPages = 1;
        }
        if (p.pageIndex > p.totalPages) {
            p.pageIndex = p.totalPages;
        }
        return p;
    }
}
